package com.compass.doctor.ui.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnCustomItemClick

import com.compass.doctor.databinding.ActivityDoctorListBinding
import com.compass.doctor.dialog.AppendDiagnoseDialog
import com.compass.doctor.ui.home.adapter.DoctorAdapter
import com.compass.doctor.ui.home.adapter.DoctorPopAdapter
import com.compass.doctor.ui.home.viewmodel.DoctorViewModel
import com.compass.framework.R
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.KEY_ORDER_ID
import com.compass.framework.constant.REFUSE_RECEPTION
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.onClick
import com.compass.framework.ext.textChangeFlow
import com.compass.framework.ext.toBeanOrNull
import com.compass.framework.ext.visible
import com.compass.framework.manager.AppManager
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.model.Dictionaries
import com.compass.framework.model.ScreenTag
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 * Description： 医生列表
 * Date:2023/12/12 16:11
 */
class DoctorListActivity : BaseVBActivity<ActivityDoctorListBinding>(), OnRefreshListener,
    OnLoadMoreListener {

    companion object {
        fun start(context: Context,comeType:Int,orderId:String) {
            val intent = Intent(context, DoctorListActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE,comeType)
            intent.putExtra(KEY_ORDER_ID,orderId)
            context.startActivity(intent)
        }
    }

    private var departmentList: ArrayList<ScreenTag> = ArrayList()
    private var positionList: ArrayList<ScreenTag> = ArrayList()
    private val doctorViewModel: DoctorViewModel by viewModels()
    private var key: String = ""
    private var windowInfoType:String="1"//1职称 2是科室
    private var comeType:Int= 1//是否跨院 1跨院    2本院(转诊)
    private var orderId:String?=null//问诊单id 转诊需要
    private var mPage = 1
    private var positionId :String? = null//职称编码
    private var departmentId :String?=null//科室编码
    private lateinit var mAdapter: DoctorAdapter
    private lateinit var listPopupWindow: ListPopupWindow
    private lateinit var popupAdapter: DoctorPopAdapter
    override fun initView(savedInstanceState: Bundle?) {
        comeType=intent.getIntExtra(KEY_CONSULT_TYPE,1)
        orderId=intent.getStringExtra(KEY_ORDER_ID)
        setPositionList()
        initRecyclerView()
        mBinding.tvTitleBar.getRightLayout().onClick {
            AppendDiagnoseDialog.Builder(this).show()
        }
        mBinding.edtDiagnosis.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击了搜索按钮后，需要隐藏软键盘
                hideSoftInput()
                key = mBinding.edtDiagnosis.text.toString().trim()
                mPage = 1
                getDoctorList()
            }
            false
        }
        mBinding.edtDiagnosis.addTextChangedListener {
            if (it.toString().isEmpty()) {
                key = mBinding.edtDiagnosis.text.toString().trim()
                mPage = 1
                getDoctorList()
            }
        }


    }

    /**
     * 格式化职称数据 哎哎哎
     */
    private fun setPositionList(){
        val list = DictionariesManager.getDoctorPosition() ?.toBeanOrNull<MutableList<Dictionaries>>()
        positionList.add(ScreenTag(null,"全部职称"))
        list?.let {
            for (item in list){
                positionList.add(ScreenTag(item.value,item.label))
            }
        }
    }

    override fun intListener() {
        mBinding.tvPositionName.onClick {
            windowInfoType="1"
            listPopupWindow.anchorView = mBinding.tvPositionName
            popupAdapter.setList(positionList)
            listPopupWindow.show()
        }
        mBinding.spDepartments.onClick {
            if(departmentList==null || departmentList.size == 0){
                showToast("请稍等，正在查询数据")
                return@onClick
            }
            windowInfoType="2"
            listPopupWindow.anchorView = mBinding.spDepartments
            popupAdapter.setList(departmentList)
            listPopupWindow.show()
        }
        mBinding.imgClose.onClick {
            mBinding.llSettingTips.visibility = View.GONE
        }

    }

    private fun initPopupWindow() {
        listPopupWindow = ListPopupWindow(this)
        popupAdapter = DoctorPopAdapter(this)
        listPopupWindow.setAdapter(popupAdapter)
        listPopupWindow.width = (AppManager.getScreenWidthPx() * 0.4).toInt()
        listPopupWindow.height = dpToPx(260)
        val bgDrawable = ContextCompat.getDrawable(
            this,
            com.compass.doctor.R.drawable.ps_permission_desc_bg
        )
        listPopupWindow.setBackgroundDrawable(bgDrawable)
        listPopupWindow.isModal = true
        popupAdapter.setOnCustomItemClick(object : OnCustomItemClick{
            override fun onItemCallBack(position: Int, value: String, label: String) {
                if (windowInfoType == "1"){
                    positionId=positionList[position].id
                    mBinding.tvPositionName.text = positionList[position].name
                }else{
                    departmentId=departmentList[position].id
                    mBinding.spDepartments.text = departmentList[position].name
                }
                listPopupWindow.dismiss()
                mPage = 1
                getDoctorList()

            }
        })
    }


    override fun initData() {
        getDoctorList()
        when(comeType){
            1->{ //跨院
                mBinding.tvPositionName.gone()
                mBinding.spDepartments.gone()
                mBinding.llSettingTips.gone()
            }
            2->{ //本院
                mBinding.llSettingTips.visible()
                mBinding.tvTips.text = getString(com.compass.doctor.R.string.referral_tips)
                mBinding.tvPositionName.visible()
                mBinding.spDepartments.visible()
                initPopupWindow()
                doctorViewModel.getDepartmentList()

            }
        }
        doctorViewModel.doctorLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                mAdapter.setData(it)
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding.emptyView.visible()
                } else {
                    mBinding.emptyView.gone()
                }
            } else {
                mBinding.refreshLayout.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    mAdapter.addAll(it)
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            }
        }

        doctorViewModel.departmentLiveData.observe(this) {
            departmentList = it as ArrayList<ScreenTag>
            departmentList.add(0, ScreenTag(null,"全部科室"))
        }
        doctorViewModel.transferLiveData.observe(this){
            LiveDataBus.get().with(REFUSE_RECEPTION).postValue( REFUSE_RECEPTION)
            showToast("转诊成功")
            finish()

        }

    }


    private fun getDoctorList() {
        doctorViewModel.getDoctorList(mPage, pageSize = 20, key, positionId, departmentId,comeType,orderId)
    }


    private fun initRecyclerView() {
        mBinding.refreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@DoctorListActivity)
            setOnLoadMoreListener(this@DoctorListActivity)
        }
        mAdapter = DoctorAdapter(comeType)
        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
        mAdapter.onItemClickListener = { _: View, position: Int ->
            val item = mAdapter.getItem(position)
            item?.let {doctor->
                if (comeType==2){
                    CommonMessageDialog.Builder(this)
                        .setTitle(getStringFromResource(R.string.dialog_tips_title))
                        .setMessage("是否将当前问诊转给医生${doctor.name}")
                        .setConfirm(getStringFromResource(R.string.default_confirm))

                        .setCancel(getString(com.compass.framework.R.string.default_cancel))
                        .setonCancelListener {
                            it?.dismiss()
                        }
                        .setonConfirmListener {
                          doctorViewModel.consultationTransfer(orderId,doctor.id)
                            it?.dismiss()
                        }.create().show()

                }else{
                    intent.putExtra("doctor", doctor)
                    setResult(RESULT_OK, intent)
                    finish()
                }
            }
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getDoctorList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getDoctorList()
    }
}